package com.ksyun.seckill.util;

import com.ksyun.seckill.rest.RestResult;
import com.ksyun.seckill.util.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     *
     */
    @ExceptionHandler(value = {ServiceException.class})
    public RestResult exceptionHandler(ServiceException ex){
        log.error(ex.getMessage());
        return RestResult.failure().msg(ex.getMessage());
    }

    /**
     * 数据格式校验错误
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public RestResult exceptionHandler(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        return RestResult.failure().data(errorMap);
    }

    @ExceptionHandler(value = {IllegalArgumentException.class})
    public RestResult exceptionHandler(IllegalArgumentException ex){
        return RestResult.failure().msg(ex.getMessage());
    }


}
